package org.phalanx.servlet.websession;

import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import org.phalanx.messenging.MessageQueue;
import org.phalanx.messenging.MessageSendable;
import org.phalanx.messenging.Messageable;
import org.phalanx.server.ServerCache.Cacheable;

public class UserWebSession implements Cacheable, MessageSendable {
	private Integer userId;
	private MessageQueue msgQ;
	private Integer feedId;
	
	public UserWebSession(Integer id){
		this.setId(id);
		msgQ = new MessageQueue();
	}
	
	@Override
	public Integer getId() {
		return userId;
	}

	@Override
	public void setId(Integer id) {
		this.userId = id;
	}
	
	@Override
	public void sendMessage(Messageable newMessage) {
		msgQ.addMessageToQueue(newMessage);
	}
	
	private String convertMessageableForHttp(Messageable newMessage){
		StringBuffer messageText = new StringBuffer();
		
		messageText.append(newMessage.getMessageHeader());
		messageText.append(":");
		messageText.append(newMessage.generateMessageBody());
		
		return messageText.toString();
	}
	
	synchronized public String getQueueThenClear(){
		StringBuffer msgData = new StringBuffer();
		
		ArrayList<Messageable> msgList = msgQ.getQueue();
		
		for (int i = 0; i < msgList.size(); i++){
			if (i > 0){
				msgData.append(";");
			}
			msgData.append("{");
			msgData.append(convertMessageableForHttp(msgList.get(i)));
			msgData.append("}");
		}
		
		msgQ.clearMessagesFromQueue();
		return msgData.toString();
	}
	
	public boolean hasQueueItems(){
		return !msgQ.getQueue().isEmpty();
	}
	
	public Integer getFeedId(){
		return feedId;
	}
	
	public void getNewFeedId(){
		Random r = new Random();
		r.setSeed(new Date().getTime());
		
		Integer newId = (r.nextInt() % 99999) + 10000;
		
		feedId = newId;
	}
	
	public boolean hasFeedId(Integer id){
		return (feedId != null && feedId.equals(id));
	}
}
